/**
 * @class fish.desktop.widget.PlanCombobox
 * 下拉框控件
 * <pre>
 *   $(element).plancombobox(option);
 * </pre>
 */

/**
 * @event open
 * 显示下拉框选项事件
 *
 * <pre>
 * $(element).on('plancombobox:open', function(e) {
 *   //do something
 * })
 * </pre>
 */
/**
 * @event close
 * 关闭下拉框选项事件
 *
 * <pre>
 * $(element).on('plancombobox:close', function(e) {
 *   //do something
 * })
 * </pre>
 */
/**
 * @event change
 * 改变下拉框值
 *
 * <pre>
 * $(element).on('plancombobox:change', function(e) {
 *   //do something
 * })
 * </pre>
 */
/**
 * @event tablechange
 * 表名变了
 *
 * <pre>
 * $(element).on('plancombobox:tablechange', function(e) {
 *   //do something
 * })
 * </pre>
 */
!function () {
    "use strict";

    //var template = `<div class="input-group ui-combobox ui-xbox">
    //                    <div class="btn-group dropup">
    //                        <button type="button" class="btn btn-default ui-xbox-table-btn">talexxx
    //                        </button>
    //                        <button type="button" class="btn btn-default ui-xbox-btn">
    //                            <span class="add_12x12"></span>
    //                        </button>
    //                    </div>
    //                </div>`,
    var template = '<div class="input-group ui-combobox ui-xbox">' +
        '        <div class="btn-group dropup">' +
        '    <button type="button" class="btn btn-default ui-xbox-table-btn">请输入表名' +
        '    </button>' +
        '    <button type="button" class="btn btn-default ui-xbox-add-btn glyphicon glyphicon-plus">' +
        '    </button>' +
        '    </div>' +
            '    </div>',
        BTN = '<button type="button" class="btn btn-default ui-xbox-btn">{0}</button>',
        MENU = '<ul class="dropdown-list"></ul>',
        MENU_ITEM = '<li></li>',
        EXTR_MENU = '<div class="dropdown-menu"></div>',
        UP_POINTER = '<div class="up-pointer"></div>',
        TABLE_INPUT = '<input type="text" class="ui-xbox-table-input"/>',
        REMOVE_BTN = '<div class="glyphicon glyphicon-remove-circle ui-xbox-remove"></div>',
        CONTAINER_INPUT = '<input type="text" class="ui-xbox-container-input"/>';

    $.widget("ui.plancombobox", {
        options: {
            dataSource: [],
            rowCount: 10000,
            /**
             * @cfg {Number} [delay=300] 延迟搜索，避免过多无效搜索，单位毫秒ms，默认是300ms
             */
            delay: 300,
            addMenuSource:[{
                name:'固定变量',
                type:'val'
            },{
                name:'时间变量',
                type:'timer',
                panel:{
                    url:webRoot+'/planmanage/addplan/jsp/timerPanel.tpl',
                    height:140,
                    render:function($extrMenu,source){
                        $extrMenu.find('input[name="cycleDayxStart"]').spinner({
                            min : "1"
                        });
                        $extrMenu.find('input[name="cycleDayxEnd"]').spinner({
                            min : "1"
                        });
                        $extrMenu.find('button[name="timer_preview_button"]').click(function(){
                        	var date_format = $extrMenu.find('input[name=date_format]:checked').val();
                        	var cycleDayxStart = $extrMenu.find('input[name="cycleDayxStart"]').val();
                        	var cycleDayxEnd = $extrMenu.find('input[name="cycleDayxEnd"]').val();
                            // var nowDate = new Date("March 31,2016 22:19:35");
                        	var nowDate = new Date();
                        	var startDate = new Date();
                        	var endDate = new Date();
                        	var y,m,d,startDateStr,endDateStr;
                        	if(date_format == 3){// 年月日
                        		startDate.setDate(nowDate.getDate() - cycleDayxStart);
                        		endDate.setDate(nowDate.getDate() - cycleDayxEnd);
                                y = startDate.getFullYear(); 
                                m = (startDate.getMonth()+1)<10?"0"+(startDate.getMonth()+1):(startDate.getMonth()+1);//获取当前月份的日期，不足10补0
                                d = startDate.getDate()<10?"0"+startDate.getDate():startDate.getDate(); //获取当前几号，不足10补0
                                startDateStr = y + "年" + m + "月" + d + "日";
                                y = endDate.getFullYear();
                                m = (endDate.getMonth()+1)<10?"0"+(endDate.getMonth()+1):(endDate.getMonth()+1);//获取当前月份的日期，不足10补0
                                d = endDate.getDate()<10?"0"+endDate.getDate():endDate.getDate(); //获取当前几号，不足10补0
                                endDateStr = y + "年" + m + "月" + d + "日";
                        	}else if(date_format == 2){// 年月
                        		startDate.setMonth(nowDate.getMonth() - cycleDayxStart);
                        		endDate.setMonth(nowDate.getMonth() - cycleDayxEnd);
                                y = startDate.getFullYear(); 
                                m = (startDate.getMonth()+1)<10?"0"+(startDate.getMonth()+1):(startDate.getMonth()+1);//获取当前月份的日期，不足10补0
                                startDateStr = y + "年" + m + "月";
                                y = endDate.getFullYear();
                                m = (endDate.getMonth()+1)<10?"0"+(endDate.getMonth()+1):(endDate.getMonth()+1);//获取当前月份的日期，不足10补0
                                endDateStr = y + "年" + m + "月";
                        	}
                        	$extrMenu.find('div[name="preview_text"]').text(endDateStr + " ~ " + startDateStr);
                        });
                    },
                    value:function($btn,value){
                        //console.info($btn,value)
                        //伪代码，设置弹出层的值
                    	var $panel = $btn.data('extrMenu');
                        var date_format = $panel.find('input[name=date_format]:checked').val(),
                            start = $panel.find('input[name=cycleDayxStart]').val(),
                            end = $panel.find('input[name=cycleDayxEnd]').val();
                        //console.info(date_format)
                        return date_format+','+start+','+end;
                    }
                }
            },{
                name:'可转换变量',
                type:'list',
                list:[{
                    label:'本地网',
                    value:1
                },{
                    label:'客户分组',
                    value:5
                },{
                    label:'清单序列',
                    value:6
                },{
                    label:'进程号',
                    value:7
                }]
            },{
                name:'账期',
                type:'4',
                panel:{
                    height:130,
                    url: webRoot+'/planmanage/addplan/jsp/rangePanel.tpl',
                    render: function($extrMenu,source){
                        $extrMenu.find('input[name="startRange"]').spinner({
                            min : "1"
                        });
                        $extrMenu.find('input[name="endRange"]').spinner({
                            min : "1"
                        });
                        $extrMenu.find('button[name="range_preview_button"]').click(function(){
                            var startRange = $extrMenu.find('input[name="startRange"]').val();
                            var endRange = $extrMenu.find('input[name="endRange"]').val();
                            // var nowDate = new Date("March 31,2016 22:19:35");
                            var nowDate = new Date();
                            var startDate = new Date();
                            var endDate = new Date();
                            var y,m,d,startDateStr,endDateStr;
                            startDate.setMonth(nowDate.getMonth() - startRange);
                            endDate.setMonth(nowDate.getMonth() - endRange);
                            y = startDate.getFullYear(); 
                            m = (startDate.getMonth()+1)<10?"0"+(startDate.getMonth()+1):(startDate.getMonth()+1);//获取当前月份的日期，不足10补0
                            startDateStr = y + "年" + m + "月";
                            y = endDate.getFullYear();
                            m = (endDate.getMonth()+1)<10?"0"+(endDate.getMonth()+1):(endDate.getMonth()+1);//获取当前月份的日期，不足10补0
                            endDateStr = y + "年" + m + "月";
                            $extrMenu.find('div[name="preview_text"]').text(endDateStr + " ~ " + startDateStr);
                        });
                    },
                    value:function($btn,value){
                        var $panel = $btn.data('extrMenu');
                        var start = $panel.find('input[name=startRange]').val(),
                            end = $panel.find('input[name=endRange]').val();
                        return start+','+end;
                    }
                }
            }]

        },
        _create: function () {
            this.$container = $(template);
            this.element.hide().before(this.$container);
            this.$tableBtn = this.$container.find('.ui-xbox-table-btn');
            this.$addBtn = this.$container.find('.glyphicon-plus');
            this.$addMenu = $(MENU).insertAfter(this.$addBtn);
            this.$tableInput = $(TABLE_INPUT).insertAfter(this.$tableBtn);
            this.$tableInput.hide();

            this.$containerInput = $(CONTAINER_INPUT).insertAfter(this.$tableBtn);
            this.$containerInput.hide();
            this._delegateEvent();
            this._initSource();
        },

        _init: function () {
            this.shown = false;
            this.selected = false;
            if (this.element.is('select')) { //如果是select，解析options
                this.options.dataSource = this._parse(); //解析select原始值
            }

            if (!this.selected) {
                this.value(this.options.value);
            }

            //this.transferAttributes();
        },
        _validateHandler: function () {
            var $element = this.element,
                that = this;
        },
        _initSource:function(){
            var me = this;
            this.sourceMaps = {};
            for(var i=0;i<me.options.addMenuSource.length;i++){
                this.sourceMaps[me.options.addMenuSource[i].type] = me.options.addMenuSource[i];
            }
        },
        _setOption: function (key, value) {
            this._super(key, value);
            if (key === "source") {
                this._initSource();
            }
            if (key === 'disabled') {
                this.$input.prop('disabled', value);
                this.$button.attr('disabled', value);
            }
        },

        /**
         * @method value 取值或者赋值
         * @param  {String} [value] 设置值选中,为空则取控件值
         * @return {String} 控件值,赋值操作则没有返回值
         */
        value: function (value) {
            if (value === undefined) {
                if(this.element.val()=='')return;
                var value = $.parseJSON(this.element.val());
                for(var i=0;i<value.length;i++){
                    if(this.sourceMaps[value[i].type]&&this.sourceMaps[value[i].type].panel&& $.isFunction(this.sourceMaps[value[i].type].panel.value)) {
                        value[i].value = this.sourceMaps[value[i].type].panel.value(this.$container.find('.ui-xbox-btn').eq(i-1),value[i].value);
                    }
                }
                this.element.val(JSON.stringify(value));
                return this.element.val();
            } else {
            	this.clear();
                if(_.isString(value)){
                    value = $.parseJSON(value);
                }
                for(var i= 0,l = value.length;i<l;i++) {
                    if(value[i].type=='table'){
                        this.$tableBtn.text(value[i].value);
                        this.checkTableChange(this.$tableBtn.text());
                    }
                    else {
                    	if(this.sourceMaps[value[i].type]&&this.sourceMaps[value[i].type].panel){
                    		this._onlyOneExtra(this.sourceMaps[value[i].type].name);	
                    	}
                        this.addItem(this.sourceMaps[value[i].type], value[i].value);
                    }
                }
                this.element.val(JSON.stringify(value));
                if(this.oldValue==null){
                    this.oldValue = this.element.val();
                }
            }
        },

        //datetimepicker提交数据的时候,界面值不是实际值,需要重写getValue方法
        _formHandler: function($form) { //增加对form的支持
            var that = this;
            $form.on('getvalue' + this.uuid + '.form', function(e) {
                return that.value();
            });
        },
        //form内置方法,根据HTML原值同步界面
        _update: function(value) {
            this.value(value);
        },

        clear: function () {
            // 清空控制时间变量和账期只能选一个的相关变量
            if(this.extras)this.extras = [];
            this.$container.find('.ui-xbox-btn').remove();
            this.$container.find('.dropdown-menu').remove();
            this.$container.find('.up-pointer').remove();
            this.element.val('');
        },

        /**
         * @method destroy
         * 销毁控件
         */
        _destroy: function () {
            this.element.prev().remove();
            this.element.show();
        },

        transferAttributes: function () {

        },

        _setDataSource: function (dataSource) {
            this.options.dataSource = dataSource;
        },

        show: function () {
            var pos = $.extend({}, this.$addBtn.position(), {
                height: this.$addBtn[0].offsetHeight
            });

            var offset = this.$addBtn.offset();
            var _height = offset.top - $(document).scrollTop() + pos.height + this.$addMenu.height();
            var parentTop = _height > $(window).height() ? -this.$addMenu.outerHeight() : (pos.top + pos.height);

            this.$addMenu.css({
                top: parentTop,
                width:this.options.addMenuWidth||130,
                left: pos.left
            });
            this.$container.addClass('open');

            this.$addMenu.on('mousedown', $.proxy(this._scrollSafety, this));
            $(document).on('click.fish.combobox', $.proxy(this.hide, this));

            this.shown = true;
            this._trigger('open');
            this.$addMenu.show();
            if(this.$selectedBtn){
                this.extraHide(this.$selectedBtn,{});
            }
        },

        hide: function () {
            this.$container.removeClass('open');
            this.$addMenu.off('mousedown', $.proxy(this._scrollSafety, this));
            $(document).off('click.fish.combobox', $.proxy(this.hide, this));
            this.shown = false;
            this._trigger('close');
            this.$addMenu.hide();
        },

        _scrollSafety: function (e) {
            if (e.target.tagName === 'UL') {
            }
        },

        lookup: function (query) {
            var that = this,
                items = $.grep(this.options.addMenuSource, function (item) {
                    return that.matcher(item, query);
                });

            items = this.sorter(items, query);

            if (!items.length) {
                return this.shown ? this.hide() : this;
            }

            return this.render(items.slice(0, parseInt(this.options.rowCount, 10)), query).show();
        },

        sorter: function (items, query) {
            var beginswith = [],
                caseSensitive = [],
                caseInsensitive = [],
                that = this;

            _.forEach(items, function (item) {
                if (!item[that.options.dataTextField].toLowerCase().indexOf(query.toLowerCase())) {
                    beginswith.push(item);
                } else if (~item[that.options.dataTextField].indexOf(query)) {
                    caseSensitive.push(item);
                } else {
                    caseInsensitive.push(item);
                }
            });

            return beginswith.concat(caseSensitive, caseInsensitive);
        },

        /*
         * 高亮显示
         * @param item
         */
        highlighter: function (item, query) {
            query = query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
            return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
                return '<strong>' + match + '</strong>';
            });
        },

        render: function (items, query) {
            var that = this;

            items = $(items).map(function (i, item) {
                i = $(MENU_ITEM).data('value', item);
                i.html(that.highlighter(item[that.options.dataTextField], query));
                return i[0];
            });

            items.first().addClass('active');
            this.$addMenu.html(items);
            return this;
        },

        matcher: function (item, query) {
            return ~item[this.options.dataTextField].toLowerCase().indexOf(query.toLowerCase()); //转换成数字0 以及非0
        },

        reset: function () {
            if (this.options.disabled) return;
            this.value(this.oldValue);
        },
        clearElement: function () {
            this.$input.val('').focus();
        },
        clearTarget: function () {
            this.element.val('');
            this._setSelected(false);
        },

        _delegateEvent: function () {

            this.$addMenu
                .on('click', $.proxy(this._onMenuClick, this))
                .on('mouseenter', 'li', $.proxy(this._onMenuMouseEnter, this))
                .on('mouseleave', 'li', $.proxy(this._onMenuMouseLeave, this));

            this.$tableBtn
                .on('click', $.proxy(this._onTableBtnClick, this));
            this.$addBtn
                .on('click', $.proxy(this._onAddBtnClick, this));

            this.$tableInput.on('blur',$.proxy(this._onTableInputBlur, this));

            this.$container.on('click',$.proxy(this._onContainerClick, this));
            this.$containerInput.on('blur',$.proxy(this._onContainerBlur, this));
            $(document.body).on('mouseover', $.proxy(this._leaveIn,this));
            //$('.ui-xbox-remove').on('click', $.proxy(this._removeItem,this));
        },
        _onContainerBlur:function(){
            this.$container.find('.ui-xbox-btn').show();
            this.$container.find('.ui-xbox-add-btn').show();
            this.$containerInput.hide();
        },
        _onContainerClick:function(e){
            e.stopPropagation();
            if(e.target!=this.$container[0]) return;
            this.$container.find('.ui-xbox-btn').hide();
            this.$container.find('.ui-xbox-add-btn').hide();
            this.$containerInput.css({
                width:this.$container.width()-this.$tableBtn.width()-23,
                height:this.$tableBtn.height()+6,
                border:0
            }).val('').show().focus();
            console.info(this.value())
            this._extraHide();
            this.hideCombo();
        },
        _onTableInputBlur:function(){
            if(this.$tableInput.val().trim().length>0) {
                this.$tableBtn.text(this.$tableInput.val());
            }
            this.$tableBtn.show();
            this.$tableInput.hide();
            this._change('table',this.$tableBtn.text(),0);

            this.checkTableChange(this.$tableBtn.text());
        },
        checkTableChange:function(newValue){
            if(this.oldTableValue!=null&&this.oldTableValue!=newValue){
                this._trigger('tablechange',null,{oldValue:this.oldTableValue,newValue:newValue});
            }
            this.oldTableValue=newValue;
        },
        _onTableBtnClick:function(e){
            e.stopPropagation();
            var inputWidth = this.$tableBtn.width()+9;
            if(inputWidth<120){
                inputWidth = 120;
            }
            this.$tableBtn.hide();
            this.$tableInput.width(inputWidth);
            this.$tableInput.height(this.$tableBtn.height()+4);
            this.$tableInput.val(this.$tableBtn.text().replace(/(^\s*)|(\s*$)/g,'')).show().focus().select();
        },
        _onAddBtnClick:function(e){
            e.stopPropagation();

            if (this.options.disabled) return;

            if (this.shown) {
                this.hide();
            } else {
                this.lookup('');
            }
            this.extraListHide(this.$selectedExtraList);
        },
        _onMenuClick: function (e) {
            e.stopPropagation();
            this._onMenuSelect();
        },
        _onMenuMouseEnter: function (e) {
            this.mousedover = true;
            this.$addMenu.find('.active').removeClass('active');
            $(e.currentTarget).addClass('active');
        },
        _onExtraMenuMouseEnter: function (e) {
            this.mousedover = true;
            this.$selectedExtraList.find('.active').removeClass('active');
            $(e.currentTarget).addClass('active');
        },
        _onMenuMouseLeave: function (e) {
            this.mousedover = false;
        },
        _onMenuSelect:function(){
            var active = this.$addMenu.find('.active'),
                item = active.data('value'),
                index = this.$addMenu.find('li').index(active),
                source = this.options.addMenuSource[index];
            this.hide();
            var name = item.name;
            var value = name;
            if(source.type==='list'){
                for(var i = 0;i<source.list.length;i++){
                    if(source.list[i].label==value) {
                        value = source.list[i].value;
                    }
                }
                name = source.list[0].label;
            }
            
            /**
        	 * 下拉框只能选一次，时间变量、账期
        	 */
        	if(source&&source.panel) {
                if(!this._onlyOneExtra(name))return;
        	}
        	
            var $btn = this.addItem(source,name);
            this._change(source.type,value);
//            if(source&&source.panel){
//                this.extraShow($btn);
//            }
        },
        _onlyOneExtra:function(name){
        	if(!this.extras) this.extras = [];
            for(var key in this.extras){
            	if(this.extras[key]){
//            		fish.toast('warn', name+'只能选一个！');
            		fish.toast('warn', '时间变量、账期只能选一个！');
            		return false;
            	}
            }
        	this.extras[name] = true;
        	return true;
        },
        _change:function(type,val,index){

            var value = $.parseJSON(this.element.val());
            if(index==undefined){
                value.push({type:type,value:val});
            }
            else{
                if(val==null){
                    delete value[index];
                }
                else {
                    value[index].value = val;
                }
            }
            var _value = [];
            for(var key in value){
                _value.push(value[key]);
            }
            this.element.val(JSON.stringify(_value));
            //console.info(this.element.val())
        },
        addItem:function(source,value){
            var menu = {btnClick:function(){}},
                $btn = $(BTN).text(value);
            menu.$btn = $btn;
            this.$addBtn.before($btn);

            if(!source){
                throw '菜单的数据源没有配置！addMenuSource';
            }
            if(source&&source.panel) {
                var $extrMenu = $(EXTR_MENU).insertAfter($btn);
                $extrMenu.css({
                    height:this.options.extraHeight||100
                });
                var $upPointer = $(UP_POINTER).insertAfter($btn);
                $btn.data('extrMenu',$extrMenu);
                $btn.data('upPointer',$upPointer);
                $extrMenu.load(source.panel.url, $.proxy(this._loadExtrMenu, this, $extrMenu,source));
                menu.btnClick = this._onExtraBtnClick;
                $btn.text(source.name);
            }
            else if(source&&source.list&&source.list.length>0){
                $btn.addClass('dropdown-toggle');
                $btn.attr({'data-toggle':"dropdown",role:"button"});

                var $extrMenu = $(MENU).insertAfter($btn);
                var displayValue;
                for(var i = 0;i<source.list.length;i++){
                    $extrMenu.append($(MENU_ITEM).text(source.list[i].label));
                    if(source.list[i].value==value){
                        displayValue = source.list[i].label;
                    }
                }
                $btn.text(displayValue);
                $extrMenu.on('click', $.proxy(this._onExtraMenuClick, this))
                    .on('mouseenter', 'li', $.proxy(this._onExtraMenuMouseEnter, this));
                $btn.data('extrMenu',$extrMenu);
                $extrMenu.data('owner',$btn);
                $btn.data('source',source);
                menu.btnClick = this._onListBtnClick;
            }
            else {
                var $btnInput = $(TABLE_INPUT).insertAfter($btn);
                $btnInput.hide();
                $btnInput.css({height:$btn.height()+6});

                $btn.data('extrMenu',$btnInput);
                $btnInput.data('owner',$btn);
                menu.btnClick = this._onInputBtnClick;
                $btnInput.on('blur',$.proxy(this._onBtnInputBlur, this,menu,$btnInput));
            }
            this._extrBtnEvent(menu);
            this._extraHide($btn);
            this._hover($btn);
            return $btn;
        },
        _onExtraMenuClick: function (e) {
            e.stopPropagation();
            var active = this.$selectedExtraList.find('.active'),
                owner = this.$selectedExtraList.data('owner'),
                index = this.$selectedExtraList.find('li').index(active),
                source = owner.data('source');
            this.extraListHide(this.$selectedExtraList);
            owner.text(source.list[index].label);
            this._change(source.type,source.list[index].value,this.$container.find('.ui-xbox-btn').index(owner)+1);
        },
        _loadExtrMenu:function($extrMenu,source){
            $extrMenu.css({height:source.panel.height});
            if($.isFunction(source.panel.render)) {
                source.panel.render($extrMenu,source);
            }
            if($.isFunction(this.options.afterrender)) {
            	this.options.afterrender($extrMenu,source);
            }
        },
        _extrBtnEvent:function(menu){
            menu.$btn.on('click', $.proxy(this._onAbstractBtnClick, this,menu));
        },
        _onAbstractBtnClick:function(menu,e){
            e.stopPropagation();
            if (this.options.disabled) return;
            this.hideCombo(menu);
            menu.btnClick.call(this,menu,e);
        },
        hideCombo:function(menu){
            if(menu)
                this._extraHide(menu.$btn);
            this.hide();
            this.extraListHide(this.$selectedExtraList);
        },
        _onInputBtnClick:function(menu,e){
            var $input = menu.$btn.data('extrMenu');
            menu.$btn.hide();
            $input.css({
                width:menu.$btn.width()+13,
                height:this.$tableBtn.height()+6
            }).val(menu.$btn.text()).show().focus();
        },
        _onBtnInputBlur:function(menu,$btnInput){
            menu.$btn.text($btnInput.val()).show();
            this._change('val',menu.$btn.text(),this.$container.find('.ui-xbox-btn').index(menu.$btn)+1);
            $btnInput.hide();
        },
        _onListBtnClick:function(menu,e){
            var $extrMenu = menu.$btn.data('extrMenu');
            this.extraListShow(menu.$btn,$extrMenu);
        },
        extraListShow: function ($owner,$extrMenu) {
            var pos = $.extend({}, $owner.position(), {
                height: $owner[0].offsetHeight
            });

            var offset = $owner.offset();
            var _height = offset.top - $(document).scrollTop() + pos.height + $extrMenu.height();
            var parentTop = _height > $(window).height() ? -$extrMenu.outerHeight() : (pos.top + pos.height);

            $extrMenu.css({
                top: parentTop,
                width:this.options.addMenuWidth||130,
                left: pos.left
            });

            $extrMenu.on('mousedown', $.proxy(this._extrScrollSafety, this));
            $(document).on('click.fish.combobox', $.proxy(this.extraListHide, this,$extrMenu));

            $extrMenu.show();
            if(this.$selectedBtn){
                this.extraHide(this.$selectedBtn,{});
            }
            this.$selectedExtraList = $extrMenu;
        },
        extraListHide: function ($extrMenu) {
            if(!$extrMenu) return;
            $extrMenu.off('mousedown', $.proxy(this._extrScrollSafety, this));
            $(document).off('click.fish.combobox', $.proxy(this.extraListHide, this));
            $extrMenu.hide();
        },
        _extrScrollSafety: function (e) {
            if (e.target.tagName === 'UL') {
            }
        },
        _onExtraBtnClick:function(menu,e){
            this.extraShow(menu.$btn);
        },
        extraShow: function ($btn) {
            var $extrMenu = $btn.data('extrMenu');
            var $upPointer = $btn.data('upPointer');
            var pos = $.extend({}, this.$container.position(), {
                height: this.$container[0].offsetHeight
            });

            var offset = this.$container.offset();
            var _height = offset.top - $(document).scrollTop() + pos.height + $extrMenu.height();
            var parentTop = _height > $(window).height() ? -$extrMenu.outerHeight() : (pos.top + pos.height);

            $extrMenu.css({
                top: parentTop+8,
                width:this.$container.width(),
                left: pos.left
            });
            $upPointer.css({
                top: parentTop,
                left:$btn.position().left+$btn.width()/2-4,
                zIndex:10001
            });
            $(document).on('click.fish.combobox', $.proxy(this.extraHide,this,$btn));
            $extrMenu.show();
            $upPointer.show();
            this.$selectedBtn = $btn;
        },
        extraHide: function ($btn,e) {
            if(e&&$btn.data('extrMenu')&&e.target!=$btn.data('extrMenu')[0]){
               this._extraHide($btn);
            }
        },
        _extraHide:function($btn){
            console.info(this.value());
            console.info($btn.data('extrMenu').find('input').isValid())
//             $btn.data('extrMenu').find('#timerForm').validator({
//		        display: function(el) {
//		            return el.getAttribute('placeholder') || '';
//		        }
//		    });
            if($btn.data('extrMenu')&&!$btn.data('extrMenu').find('input').isValid()){
                return;
            }
            $(document).off('click.fish.combobox', $.proxy(this.extraHide,this,$btn));
            this.$container.find('.dropdown-menu').hide();
            this.$container.find('.up-pointer').hide();
        },
        _hover:function($btn){
            var $remove = $(REMOVE_BTN).appendTo(this.$container);
            $remove.on('click',$.proxy(this._removeItem,this,$remove));
            $btn.data('remove_icon',$remove);
        },
        _leaveIn:function(e){
            if(e.target.className.indexOf('ui-xbox-remove')==-1){
                this._leaveOut();
            }
            if(e.target.className.indexOf('ui-xbox-btn')!=-1) {
                var $remove = $(e.target).data('remove_icon').show();
                var pos = $.extend({}, $(e.target).position(), {
                    height: $(e.target)[0].offsetHeight
                });
                $remove.css({
                    top: pos.top -18,
                    left:pos.left+$(e.target).width()-3
                });
            }
        },
        _leaveOut:function(){
            $('.ui-xbox-remove').hide();
        },
        _removeItem:function($remove){
            var index = this.$container.find('.ui-xbox-remove').index($remove);
            $remove.off('click',$.proxy(this._removeItem,this,$remove));
            var $btn = this.$container.find('.ui-xbox-btn').eq(index);
            if(this.extras&&this.extras[$btn.text()])this.extras[$btn.text()] = false;

            var $extrMenu = $btn.data('extrMenu');
            if($extrMenu){
                $extrMenu.remove();
            }
            var $upPointer = $btn.data('upPointer');
            if($upPointer){
                $upPointer.remove();
            }
            $remove.remove();
            this._change(null,null,index+1);
            $btn.remove();
        }

    });
}();